package com.hay.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;

/**
 * @title: UploadService
 * @Author HuangYan
 * @Date: 2020/7/21 19:52
 * @Version 1.0
 */
@Service
public class UploadService {

    private static final List<String> CONTENT_TYPE = Arrays.asList("image/jpeg","image/gif","image/png");
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    @Autowired
    private FastFileStorageClient storageClient;

    public String uploadImages(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        // 验证文件类型
        String contentType = file.getContentType();
        if (!CONTENT_TYPE.contains(contentType)){
            LOGGER.info("文件类型不合法：{}",originalFilename);
            return null;
        }
        // 验证文件内容
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null){
                LOGGER.info("文件内容不合法：{}",originalFilename);
                return "null";
            }

            // 获取文件后缀
            String ext = StringUtils.substringAfterLast(originalFilename, ".");

            // 保存文件
            //file.transferTo(new File("D:\\IDEAWorkspace\\leyou\\images\\" + originalFilename));
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);

            // 回显url
            //return "http://image.leyou.com/" + originalFilename;
            System.out.println("http://image.leyou.com/" + storePath.getFullPath());
            return "http://image.leyou.com/" + storePath.getFullPath();

        } catch (Exception e){
            LOGGER.info("服务器内部错误：{}", originalFilename);
            e.printStackTrace();
        }
        return null;
    }
}
